﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using static Dapper.SqlMapper;

namespace Respository.Base
{
    public class RepositoryBase : IRepositoryBase//RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : class,new()
    {
        public List<TEntity> QuerySPList<TEntity>(string SPName)
        {
            using (IDbConnection Conn = SqlServerRespository.SqlServerContext.GetSqlConnection())
            {
                return Conn.Query<TEntity>(SPName, null, null, true, 0, CommandType.StoredProcedure).AsList();
            }
        }

        public List<TEntity> QuerySPList<TEntity>(string SPName, object parms)
        {
            using (IDbConnection Conn = SqlServerRespository.SqlServerContext.GetSqlConnection())
            {
                return Conn.Query<TEntity>(SPName, parms, null, true, 0, CommandType.StoredProcedure).AsList();
            }
        }

        public async Task<TEntity> QueryFirstAsync<TEntity>(string Sql,object parms,CommandType commandType)
        {
            using (IDbConnection Conn = SqlServerRespository.SqlServerContext.GetSqlConnection())
            {
                // return await Task.Run(() => conn.Query<T>(SPName, null, null, true, null, CommandType.StoredProcedure).ToList());
                return await Conn.QueryFirstOrDefaultAsync<TEntity>(Sql,parms, null,  0, commandType);
            }
        }

        public async Task<List<TEntity>> QuerySPListAsync<TEntity>(string SPName)
        {
            using (IDbConnection Conn = SqlServerRespository.SqlServerContext.GetSqlConnection())
            {
                // return await Task.Run(() => conn.Query<T>(SPName, null, null, true, null, CommandType.StoredProcedure).ToList());
                return (await  Conn.QueryAsync<TEntity>(SPName, null, null,0, CommandType.StoredProcedure)).AsList();
            }
        }

        public async Task<List<TEntity>> QuerySPListAsync<TEntity>(string SPName, object parms)
        {
            using (IDbConnection Conn = SqlServerRespository.SqlServerContext.GetSqlConnection())
            {
               return (await Conn.QueryAsync<TEntity>(SPName, parms, null, 0, CommandType.StoredProcedure)).AsList();
            }
        }

        public async Task<DataSet> QueryDataSet(string Sql, object parms, CommandType commandType)
        {
            var ds = new DataSet();
            using (IDbConnection Conn = SqlServerRespository.SqlServerContext.GetSqlConnection())
            {
                var reader = await Conn.ExecuteReaderAsync(Sql, parms, null, 0, commandType);
                int i = 0;
                while (!reader.IsClosed)
                {
                    ds.Tables.Add($"table{i}");
                    ds.Tables[i].Load(reader);
                    i++;
                }
            }
            return ds;
        }
    }
}
